import { connect } from 'dva';
import React, { useState, useEffect } from 'react';
import { Upload, Icon, message, Row, Col } from 'antd';
import { userId } from '@/constant';
const creator = (type, payload) => ({ type, payload });
function BasicInfo(props) {
  const { dispatch, history } = props;
  const id = window.sessionStorage.getItem(userId);
  useEffect(() => {
    const { location } = history;
    const { query } = location;
    const { name } = query;
    dispatch(creator('users/getUser', { id }));
  }, [dispatch, history, id]);

  //loading
  const [loading, setLoading] = useState(false);
  //imageUrl
  const [imageUrl, setImageUrl] = useState('');

  const uploadButton = (
    <span style={{ display: 'inline-block', marginTop: 60, fontSize: 12, color: '#ccc' }}>
      <Icon type="plus" />
      <br />
      <span>图片格式为png/jpg</span>
      <span>宽高像素不低于320px*320px</span>
    </span>
  );
  const handleChange = info => {
    if (info.file.status === 'uploading') {
      // this.setState({ loading: true });
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(
        info.file.originFileObj,
        imgUrl =>
          // setLoading(false),

          setImageUrl(imgUrl),
        dispatch(creator('users/getUser', { id })),
      );
    }
  };
  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }
  function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传jpg或png类型的图片！');
      return false;
    }
    return new Promise((resolve, reject) => {
      let _URL = window.URL || window.webkitURL;
      let img = new Image();
      img.onload = function() {
        var ww = img.width;
        var hh = img.height;
        let valid = ww < 320 || hh < 320;
        console.log(valid);
        !valid ? resolve() : reject();
      };
      img.src = _URL.createObjectURL(file);
    }).then(
      () => {
        return file;
      },
      () => {
        message.error(file.name + '图片尺寸不符合要求，请修改后重新上传！');
        return Promise.reject();
      },
    );
  }
  const { users } = props.users;
  return (
    <div style={{ margin: 20 }}>
      <h2>个人信息</h2>

      <Row>
        <Col span={4} style={{ height: '164px', lineHeight: '164px', textAlign: 'center' }}>
          头像：
        </Col>
        <Col span={20}>
          <Upload
            style={{ display: 'inline-block', height: '180px', width: '180px' }}
            name="avatar"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action="api/users/updateAvatar"
            beforeUpload={beforeUpload}
            onChange={handleChange}
            data={{ id }}
            // headers={{'content-type':'application/json;charset=utf-8'}}
          >
            {users.length ? (
              <img
                src={users.length ? users[0].avatar : imageUrl}
                alt="avatar"
                style={{ width: '100%', width: '164px', height: '164px' }}
              />
            ) : (
              uploadButton
            )}
            {/* {uploadButton} */}
          </Upload>
        </Col>
      </Row>
      <Row>
        <Col span={4}>用户名：</Col>
        <Col span={20}>{users.length ? users[0].username : ''}</Col>
      </Row>

      <Row>
        <Col span={4}>性别：</Col>
        <Col span={20}>{users.length ? users[0].sex : ''}</Col>
      </Row>
      <Row>
        <Col span={4}>所处阶段：</Col>
        <Col span={20}>{users.length ? users[0].lifestage : ''}</Col>
      </Row>
      <Row>
        <Col span={4}>个人邮箱：</Col>
        <Col span={20}>{users.length ? users[0].email : ''}</Col>
      </Row>
      <Row>
        <Col span={4}></Col>
        <Col span={20}></Col>
      </Row>
    </div>
  );
}

export default connect(({ users }) => ({ users }))(BasicInfo);
